package com.copa.provider.news;

import com.copa.entity.News;
import com.copa.service.NewsService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;

/**
 * @author copa
 * @createDate 2022-02-23 09:40
 * @function 百度实时热搜
 */
@Component
public class BaiduTopNews {

    @Autowired
    private NewsService newsService;

    public void getNews() {
        try {
            Document document = Jsoup.connect("https://top.baidu.com/board?tab=realtime")
                    .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36")
                    .get();
            Elements oneNewsEle = document.getElementsByClass("category-wrap_iQLoo horizontal_1eKyQ");
            int id = 0;
            for (Element element : oneNewsEle) {
                id++;
                String title = element.getElementsByClass("c-single-text-ellipsis").get(0).text();
                String encodeTitle = URLEncoder.encode(title, "utf-8");
                String href = "https://www.baidu.com/s?wd=" + encodeTitle + "&sa=fyb_news&rsv_dl=fyb_news";
                String hotNum = element.getElementsByClass("hot-index_1Bl1a").get(0).text();
                String imageUrl = element.getElementsByTag("img").attr("src");
                News news = News.builder()
                        .topNum(id)
                        .title(title)
                        .hotNum(hotNum)
                        .href(href)
                        .time(LocalDate.now())
                        .imageUrl(imageUrl)
                        .build();
                newsService.insert(news);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
